package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WechatServiceImpl implements WechatService {
    public static final String GET_OPENID_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    public static final String GET_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";

    public static final String GET_PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    @Value("${wechat.appid}")
    private String appid;
    @Value("${wechat.secret}")
    private String secret;

    public Map<String, Object> getConfig(){
        HashMap<String, Object> map = new HashMap<>();
        map.put("appid", appid);
        map.put("secret", secret);
        return map;
    }

    @Override
    public String getOpenId(String code) {
        Map<String, Object> map = getConfig();
        map.put("js_code", code);
        String result = HttpUtil.get(GET_OPENID_URL, map);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if(ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))){
            throw new BaseException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getStr("openid");
    }

    @Override
    public String getPhone(String phoneCode) {
        String token = getToken();
        String url = GET_PHONE_URL + token;
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", phoneCode);
        String result = HttpUtil.post(url, JSONUtil.toJsonStr( map));
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if(jsonObject.getInt("errcode")!=0){
            throw new BaseException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
    }

    public String getToken(){
        Map<String, Object> map = getConfig();
        map.put("grant_type", "client_credential");
        String result = HttpUtil.get(GET_TOKEN_URL, map);

        JSONObject jsonObject = JSONUtil.parseObj(result);
        if(ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))){
            throw new BaseException(jsonObject.getStr("errmsg"));
        }

        return jsonObject.getStr("access_token");
    }
}
